package com.itmuch.usercenter.service.user;

import com.itmuch.usercenter.dao.user.UserMapper;
import com.itmuch.usercenter.domain.dto.user.UserLoginDto;
import com.itmuch.usercenter.domain.entity.user.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author caiqian
 * @date 2021/5/7 8:33
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class UserService {
    private final UserMapper userMapper;

    public User findById(Integer id) {
        log.info("我被请求了!");
        return this.userMapper.selectByPrimaryKey(id);
    }

    public User login(UserLoginDto loginDto, String openId) {
        //看用户是否注册，如果没有注册就注册
        //如果已经注册，就颁发token
        User user = this.userMapper.selectOne(
                User.builder()
                        .wxId(openId)
                        .build()
        );

        if (user == null) {
            User userToSave = User.builder()
                    .wxId(openId)
                    .wxNickname(loginDto.getWxNickName())
                    //初始化积分为300
                    .bonus(300)
                    //初始化为普通用户
                    .roles("user")
                    .createTime(new Date())
                    .updateTime(new Date())
                    .avatarUrl(loginDto.getAvatarUrl())
                    .build();

            this.userMapper.insertSelective(userToSave);

            return userToSave;

        }

        return user;
    }
}
